package com.dalongxin.work.page;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.dalongxin.work.Constants;
import com.dalongxin.work.EventCenter;
import com.dalongxin.work.R;
import com.dalongxin.work.data.Buy;
import com.dalongxin.work.page.adapter.BuyAdapter;
import com.dalongxin.work.utils.HttpUtil;
import com.dalongxin.work.utils.ItemClickSupport;
import com.dalongxin.work.utils.StatusBarUtil;
import com.dalongxin.work.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 采购计划列表
 */
@ContentView(R.layout.activity_common_list)
public class DjBuyActivity extends BaseActivity implements View.OnClickListener {

    @ViewInject(R.id.tool_bar)
    private Toolbar toolbar;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.recycler_view)
    private RecyclerView recyclerView;
    @ViewInject(R.id.xrefreshview)
    private XRefreshView xRefreshView;

    @ViewInject(R.id.image_no_data)
    private View mNoDataImg;
    @ViewInject(R.id.normal_tips_view)
    private TextView mNormalTipsView;
    @ViewInject(R.id.special_layout)
    private LinearLayout mSpecialLayout;
    @ViewInject(R.id.first_tips)
    private TextView mFirstTipsView;
    @ViewInject(R.id.second_tips)
    private TextView mSecondTipsView;

    private int lastId = 0;
    private int companyId = 0;//公司ID
    private String contractName;//合同名称
    private int filter = 0;//0：所有 1：需要我审核的 2：我创建的
    private int projectId;//项目ID
    private List<Buy> mData;
    private BuyAdapter mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        EventBus.getDefault().register(this);
        this.setSupportActionBar(toolbar);//这样menu才能显示出来
        getSupportActionBar().setDisplayShowTitleEnabled(false);//去掉默认title的显示
        StatusBarUtil.setPaddingSmart(this, toolbar);
        StatusBarUtil.darkMode(this, false);
        titleText.setText("采购计划");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initEmptyView();

        mData = new ArrayList<>();
        mAdapter = new BuyAdapter(mData);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        // 静默加载模式不能设置footerview
        recyclerView.setAdapter(mAdapter);
        //设置刷新完成以后，headerview固定的时间
        //xRefreshView.setPinnedTime(1000);
        xRefreshView.setMoveForHorizontal(true);
        //xRefreshView1.setAutoLoadMore(true);
        mAdapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        //设置静默加载时提前加载的item个数
        //xRefreshView1.setPreLoadCount(4);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh(boolean isPullDown) {
                lastId = 0;
                getDataList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                getDataList();
            }
        });
        ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, View itemView, int position) {
                Buy item = mData.get(position);
                Intent intent = new Intent(DjBuyActivity.this, DjBuyNewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("BEAN", item);
                intent.putExtra(DjHtspNewActivity.IS_EDIT, 1);
                intent.putExtra("bundle",bundle);
                startActivity(intent);
            }
        });
        xRefreshView.setPullRefreshEnable(true);//允许下拉刷新
        xRefreshView.setPullLoadEnable(false);//禁止加载更多
        xRefreshView.setEmptyView(mNoDataImg);
        xRefreshView.setAutoRefresh(true);
    }

    private void initEmptyView() {
        mNormalTipsView.setVisibility(View.GONE);
        mSpecialLayout.setVisibility(View.VISIBLE);
        mFirstTipsView.setText(getString(R.string.class_cloud_disk_empty_first_tips));
        mSecondTipsView.setText(getString(R.string.class_cloud_disk_empty_second_tips));
    }

    private void getDataList() {
        Map<String, String> params = new HashMap<>();
        params.put("companyId", String.valueOf(companyId));
        params.put("filter", String.valueOf(filter));
        params.put("projectId", String.valueOf(projectId));
        params.put("lastId", String.valueOf(lastId));
        HttpUtil.getInstance().post(true, Constants.url_getBuyList, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    List<Buy> temp = Buy.parseFromJsonList(response.optJSONArray("data"));
                    if(temp != null) {
                        if(lastId == 0) {
                            mData.clear();
                        }
                        mData.addAll(temp);
                        if(Constants.pageSize > temp.size()) {
                            xRefreshView.setPullLoadEnable(false);
                        }
                    }else {
                        xRefreshView.setPullLoadEnable(false);
                    }
                    mAdapter.notifyDataSetChanged();
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                xRefreshView.stopRefresh();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.danju_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem menuShaixuan = menu.findItem(R.id.menu_shaixuan);
        MenuItem menuNew = menu.findItem(R.id.menu_new);
        menuShaixuan.setVisible(true);
        menuNew.setVisible(true);
        menuNew.setTitle("新建采购计划");
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_shaixuan:
                Intent selectIntent = new Intent(this, SelectionActivity.class);
                startActivityForResult(selectIntent, SelectionActivity.REQ_SELECT);
                break;
            case R.id.menu_new:
                Intent newIntent = new Intent(this, DjBuyNewActivity.class);
                startActivity(newIntent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventBus(EventCenter event) {
        if(event.getEventType() == EventCenter.BUY_REFRESH) {
            getDataList();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode == SelectionActivity.REQ_SELECT && resultCode == RESULT_OK) {
            if(data != null) {
                Map<Integer, Integer> chooseMap = (Map<Integer, Integer>)data.getSerializableExtra(SelectionActivity.SELECT_PARAMS);
                Iterator<Map.Entry<Integer, Integer>> it = chooseMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<Integer, Integer> entry = it.next();
                    LogUtil.e("key = " + entry.getKey() + ", value = " + entry.getValue());
                    if(entry.getKey() == 0) {
                        if(entry.getValue() != -1) {
                            companyId = entry.getValue();
                        }else {
                            companyId = 0;
                        }
                    }
                    if(entry.getKey() == 1) {
                        if(entry.getValue() != -1) {
                            projectId = entry.getKey();
                        }else {
                            projectId = 0;
                        }
                    }
                    if(entry.getKey() == 2) {
                        if(entry.getValue() != -1) {
                            filter = entry.getKey();
                        }else {
                            filter = 0;
                        }
                    }
                    getDataList();
                }
            }
        }
    }
}
